﻿using Check_Barcode;
using com.google.zxing;
using com.google.zxing.common;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Check_Barcode
{
    public partial class AForge_Barcode_Check : DevComponents.DotNetBar.Office2007Form
    {
        SoftReg softReg = new SoftReg();
        public AForge_Barcode_Check()
        {
            InitializeComponent();
        }

        private void AForge_Barcode_Check_Load(object sender, EventArgs e)
        {
            string[] cols1 = {  "标准条码", "扫描条码",  "作业时间", "校验状态" };
            string[] names1 = {  "SN1", "SN2",  "Operation_time", "iCheck_sta" };
            initDataView(Scan_list, cols1, names1);
            _试用软件();
        }
        #region 试用软件
        public void _试用软件()
        {
            try
            {
                //判断软件是否注册
                RegistryKey retkey = Registry.CurrentUser.OpenSubKey("SOFTWARE", true).CreateSubKey("C001").CreateSubKey("Register.INI");
                foreach (string strRNum in retkey.GetSubKeyNames())
                {
                    if (strRNum == softReg.GetRNum())
                    {
                        this.Text += "  [已注册]";
                        //this.labRegInfo.Text = "此软件已注册！";
                        //this.btnReg.Enabled = false;
                        return;
                    }
                }
                this.Text += "  [未注册]";
                //this.labRegInfo.Text = "此软件尚未注册！";
                //this.btnReg.Enabled = true;
                MessageBox.Show("您现在使用的是试用版，可以免费试用30次！", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);

                Int32 tLong;    //已使用次数
                try
                {
                    tLong = (Int32)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\C001", "UseTimes", 0);
                    MessageBox.Show("您已经使用了" + tLong + "次！", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch
                {
                    MessageBox.Show("欢迎使用本软件！", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Registry.SetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\C001", "UseTimes", 0, RegistryValueKind.DWord);
                }
                //判断是否可以继续试用
                tLong = (Int32)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\C001", "UseTimes", 0);
                if (tLong < 30)
                {
                    int tTimes = tLong + 1;
                    Registry.SetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\C001", "UseTimes", tTimes);
                }
                else
                {
                    DialogResult result = MessageBox.Show("试用次数已到！您是否需要注册？", "信息", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                    if (result == DialogResult.Yes)
                    {
                        FormRegister.state = false; //设置软件状态为不可用
                        //btnReg_Click(sender, e);    //打开注册窗口
                    }
                    else
                    {
                        Application.ExitThread();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("请以管理员身份运行!" + ex.Message);
                this.Close();
            }

        }
        #endregion

        private void select_img_Click(object sender, EventArgs e)
        {
            try
            {
                panelEx1.Text = "";
               
                if (this.openFileDialog1.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                //select_img.Enabled = false;
                Image img = Image.FromFile(this.openFileDialog1.FileName);
                Bitmap bmap;
                try
                {
                    bmap = new Bitmap(img);
                }
                catch (System.IO.IOException ioe)
                {
                    MessageBox.Show(ioe.ToString());
                    return;
                }
                if (bmap == null)
                {
                    MessageBox.Show("Could not decode image");
                    return;
                }
                panelEx1.Style.BackgroundImage = img;
                LuminanceSource source = new RGBLuminanceSource(bmap, bmap.Width, bmap.Height);
                com.google.zxing.BinaryBitmap bitmap1 = new com.google.zxing.BinaryBitmap(new HybridBinarizer(source));
                Result result;
                try
                {
                    result = new MultiFormatReader().decode(bitmap1);
                }
                catch (ReaderException re)
                {
                    MessageBox.Show("识别失败！\r\n"+re.ToString());
                    return;
                }
                Read_Barcode.Text = result.Text;
                if (!string.IsNullOrEmpty(Read_Barcode.Text))
                {
                    panel1.BackColor = Color.GreenYellow;
                }
                else
                {
                    panel1.BackColor = Color.Pink;
                }
                Scan_Barcode.Focus();
                select_img.Enabled = true;
            }
            catch (Exception EX)
            {
                MessageBox.Show("识别失败！"+EX.ToString());
            }
        }

        #region 初始化表格
        public void initDataView(DataGridView dataView, string[] cols, string[] names)
        {
            dataView.AllowUserToAddRows = false;
            dataView.AllowUserToDeleteRows = false;
            dataView.AllowUserToOrderColumns = false;
            dataView.AllowUserToResizeRows = false;
            for (int i = 0; i < cols.Length; i++)
            {
                DataGridViewColumn _col = new DataGridViewTextBoxColumn();
                _col.Name = cols[i];
                _col.HeaderText = cols[i];
                _col.ReadOnly = true;
                _col.DataPropertyName = names[i];
                dataView.Columns.Add(_col);
            }
            dataView.AutoGenerateColumns = false;
            dataView.RowsDefaultCellStyle.BackColor = Color.FromArgb(239, 240, 248);//ColorTranslator.FromHtml("#EFF0F8"); ;//隔行变色;
            dataView.AlternatingRowsDefaultCellStyle.BackColor = Color.White;//隔行变色
        }
        #endregion 初始化表格

        #region _NG处理
        public void _NG处理()
        {
            Thread thread = new Thread(new ThreadStart(NG_BackColor));
            thread.Start();//NG闪背景
        }
        public void _PASS处理()
        {
            Thread thread = new Thread(new ThreadStart(PASS_BackColor));
            thread.Start();//NG闪背景
        }
        //panel颜色变化
        private void NG_BackColor()
        {
            for (int i = 0; i < 6; i++)
            {
                panelEx3.Style.BackColor2.Color = Color.FromArgb(175, 210, 255);
                Thread.Sleep(200);
                panelEx3.Style.BackColor2.Color = Color.Red;
                Thread.Sleep(200);

            }
        }
        //panel颜色变化
        private void PASS_BackColor()
        {
            for (int i = 0; i < 3; i++)
            {
                panelEx3.Style.BackColor2.Color = Color.FromArgb(175, 210, 255);
                Thread.Sleep(200);
                panelEx3.Style.BackColor2.Color = Color.Green;
                Thread.Sleep(200);
            }
        }
        #endregion


        private void CountPlus()
        {
            label_Count.Text = (Convert.ToInt32(label_Count.Text) + 1).ToString();
        }

        private void Scan_Barcode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData != Keys.Enter)
            {
                return;
            }
            if (Scan_Barcode.Text.Trim() == "")
            {
                return;
            }
            #region 条码规则校验
            string _主板条码规则 = Read_Barcode.Text.Trim();
            if (Scan_Barcode.Text.Length != _主板条码规则.Length)
            {
                _NG处理();
                MessageBox.Show("条码长度不正确");
                Scan_Barcode.SelectAll();
                Scan_Barcode.Focus();
                return;
            }
            for (int i = 0; i < _主板条码规则.Length; i++)
            {
                if (_主板条码规则[i].ToString() != "*")
                {
                    if (Scan_Barcode.Text.ToString()[i].ToString() != _主板条码规则[i].ToString())
                    {
                        _NG处理();
                        MessageBox.Show("条码第" + (i + 1).ToString() + "位字符不正确！");
                        Scan_Barcode.SelectAll();
                        Scan_Barcode.Focus();
                        return;
                    }
                }
            }
            #endregion
            _PASS处理();
            CountPlus();
            Scan_list.Rows.Add();
            Scan_list.Rows[Scan_list.RowCount - 1].Cells["标准条码"].Value = Read_Barcode.Text;
            Scan_list.Rows[Scan_list.RowCount - 1].Cells["扫描条码"].Value = Scan_Barcode.Text.Trim();
            Scan_list.Rows[Scan_list.RowCount - 1].Cells["作业时间"].Value = DateTime.Now.ToString();
            Scan_list.Rows[Scan_list.RowCount - 1].Cells["校验状态"].Value = "PASS";

            Scan_Barcode.Text = "";

        }

        private void Scan_list_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            try
            {
                Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
                    Convert.ToInt32(e.RowBounds.Location.Y + (e.RowBounds.Height - Scan_list.RowHeadersDefaultCellStyle.Font.Size) / 2),
                     Scan_list.RowHeadersWidth - 4, e.RowBounds.Height);
                TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
                     Scan_list.RowHeadersDefaultCellStyle.Font, rectangle, Scan_list.RowHeadersDefaultCellStyle.ForeColor,
                    TextFormatFlags.Right);
            }
            catch (Exception ex)
            {
                Console.Write("dgv1_RowPostPaint：" + ex.Message);
            }
            string cf = Convert.ToString(Scan_list.Rows[e.RowIndex].Cells["校验状态"].Value);
            if (cf == "PASS")//
            {
                this.Scan_list.Rows[e.RowIndex].Cells["校验状态"].Style.BackColor = Color.GreenYellow;
            }
            if (cf == "NG")//
            {
                this.Scan_list.Rows[e.RowIndex].Cells["校验状态"].Style.BackColor = Color.Yellow;
            }
        }

        private void exitMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult TS = MessageBox.Show("您确认要退出系统吗？", "系统消息", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (TS == DialogResult.Yes)
            {
                // e.Cancel = false;
                // Application.Exit();
                Application.ExitThread();
            }
            else
            {
                //e.Cancel = true;
            }
        }
    }
}
